package cn.gson.CRM.service.product;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.HttpRequestHandlerServlet;
import org.springframework.web.multipart.MultipartFile;


@Service
public class UploadImg {

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy" + "/" + "MM");

	/**
	 * 允许上传的后缀
	 */
	private List<String> exts;

	private File root;

	public UploadImg() {
		String e="png,jpg,gif,jpeg";
		this.exts = Arrays.asList(e.split(","));
		
//		String path =  re.getServletContext().getContextPath();
//		System.out.println("0000000"+path);
		File r = new File("D:/project/crm/upload");
		if (!r.exists()) {
			// 如果目录部不存在就创建出来
			r.mkdirs();
		}
		this.root = r;
	}
	
	/**
	 * 保存文件
	 * 
	 * @param mf
	 * @return
	 */
	public String save(
//			User user, 
			MultipartFile mf
			,HttpServletRequest request) {
		// 判断文件是否允许保存，根据后缀判断
		// 文件的原始名称
		String orgName = mf.getOriginalFilename();
		String path=request.getSession().getServletContext().getRealPath("uploadImage/");
		System.out.println(path);
		// 获取文件后缀
		String ext = FilenameUtils.getExtension(orgName);
		String newFileName;
		String timePath = sdf.format(new Date());
		if (exts.contains(ext)) {
			// 生成新的文件名称
			newFileName = UUID.randomUUID().toString() + "." + ext;

			/// Users/gson/upload/2018/01/文件名称.xxx
			// 构建一个存储路径
			File savePath = new File(path, timePath);
			if (!savePath.exists()) {
				savePath.mkdirs();
			}
			// 存储文件
			try {
				mf.transferTo(new File(savePath, newFileName));
				
				String imgName = "uploadImage"+"/"+timePath+"/"+newFileName;
				System.out.println(imgName);

				return imgName;
			} catch (Exception e) {
				throw new UploadException("文件上传失败！", e);
			}
		} else {
			throw new UploadException(String.format("不支持[%s]此类型文件上传！", ext));
		}
	}

	public File get(String filePath) {
		File file = new File(root, filePath);
		if (!file.exists()) {
			throw new UploadException("[" + filePath + "]文件不存在！");
		}
		return file;
	}

	public void delete(String filePath) {
		File file = new File(root, filePath);

		if (!file.exists()) {
			throw new UploadException("[" + filePath + "]文件不存在！");
		}

		file.deleteOnExit();
	}
}
